import {computed, type Ref} from 'vue'
import type InputProps from "@/components/input/type/InputProps.ts";
import type InputEmits from "@/components/input/type/InputEmits.ts";
import {mixHexWithWhite, normalizeValue} from "@/components/utils.ts";

/**
 * created by yangtong on 2025/6/16 下午11:02
 * <br />
 * 输入框辅助功能
 */
export function useInputHelpers(props: InputProps) {

    // 边框颜色处理
    const lightBorderColor = computed(() =>
        mixHexWithWhite(props.borderColor!, 0.85)
    )

    // 输入限制检查
    const allowsCheck = (val: string): boolean => {
        if (!val || val.length === 0) return true

        if (props.allows && props.allows.length > 0) {
            for (let allow of props.allows) {
                if (!allow(val)) {
                    console.warn(`allow校验失败【${allow}】，不允许输入内容【${val}】`)
                    return false
                }
            }
        }

        return true
    }

    // 格式化值
    const formatValue = (val: string | number | null | undefined): string => {
        const normalizedVal = normalizeValue(val)
        return props.format && normalizedVal.length > 0 ? props.format(normalizedVal) : normalizedVal
    }

    // 解析值
    const parseValue = (val: string): string => {
        return props.parse ? props.parse(val) : val
    }

    // 清空输入
    const cleanInput = (emit: InputEmits, displayValue: Ref<string>) => {
        displayValue.value = ""
        emit('update:modelValue', "")
    }

    return {
        lightBorderColor,
        allowsCheck,
        formatValue,
        parseValue,
        cleanInput
    }

}